package com.xrh.core.annotation;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;


/**
 * @function 字符串整校验
 * @author 肖荣辉
 * @date 2023年12月8日
*/
@Documented
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@Constraint(validatedBy = {InStrValidation.InValidator.class})
@Repeatable(InStrValidation.List.class)
public @interface InStrValidation {
    String message() default "不在指定值域";

    String[] value() default {};

    //默认不允许为空
    boolean nullable() default false;

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    @Documented
    @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
    @Retention(RUNTIME)
    @interface List {
        InStrValidation[] value();
    }

    class InValidator implements ConstraintValidator<InStrValidation, Object> {

        private InStrValidation inValidation;

        @Override
        public void initialize(InStrValidation inValidation) {
            this.inValidation = inValidation;
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext context) {
            if (value == null) {
                return inValidation.nullable();
            }
            String[] values = inValidation.value();
            for (String o : values) {
                if (value.equals(o)) {
                    return true;
                }
            }
            return false;
        }
    }
}